package com.zhiyizhen.handheld.common;

import android.content.Context;
import android.os.Environment;

import androidx.annotation.NonNull;

import com.zhiyizhen.handheld.net.BaseObserver;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;

/**
 * description 本地图片管理类，主要用于拍照之后的压缩图片的管理
 */
public class PictureManager {

    private static final PictureManager INSTANCE = new PictureManager();

    private PictureManager() {
    }

    public static PictureManager getInstance() {
        return INSTANCE;
    }

    public File getCompressFilePath(Context context) {
        return context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    }

    public void asyncDelete(final Context context) {
        Observable.create((ObservableOnSubscribe<String>) emitter -> {
                    delete(context);

                    emitter.onNext("");
                    emitter.onComplete();
                })
                .compose(RxJavaUtil.mainSchedulers())
                .subscribe(new BaseObserver<>() {
                    @Override
                    public void onNext(@NonNull String str) {
                        LogUtil.d(str);
                    }
                });
    }

    private void delete(Context context) {
        File path = getCompressFilePath(context);
        if (!path.exists() || !path.isDirectory()) {
            return;
        }

        File[] files = getCompressFilePath(context).listFiles();
        if (files == null) {
            return;
        }

        for (File file : files) {
            if (file.exists() && file.isFile()) {
                boolean result = file.delete();
                LogUtil.d("delete file " + file.getAbsolutePath() + " result " + result);
            }
        }
    }

}
